<template>
	<view class="mian" style="background-color: #fff; padding: 0 20rpx;">
		<u--form labelPosition="left" :model="form" ref="uForm" labelWidth='160rpx'>
			<u-form-item label="商品名称" prop="store_name" borderBottom>
				<u--input v-model="form.store_name" border="none" placeholder="请输入商品名称"></u--input>
			</u-form-item>
			</u-form-item>
			<u-form-item label="商品简介" prop="store_info" borderBottom>
				<u--input v-model="form.store_info" border="none" placeholder="请输入商品简介"></u--input>
			</u-form-item>
			<u-form-item label="排序" borderBottom>
				<u--input v-model="form.sort" border="none" type='numder' minNum='0' placeholder="请输入商品排序"></u--input>
			</u-form-item>
			<u-form-item label="商品封面图" prop="image">
				<u-upload accept="image" @afterRead="afterRead(1,$event)" @delete="(event, type) => deletePic(event, 1)"
					multiple :maxCount="1" width="210rpx" height="210rpx" :fileList="imageArr"
					:sizeType="['compressed']">
				</u-upload>
			</u-form-item>
			<u-form-item label="商品轮播图" prop="slider_image">
				<u-upload accept="image" @afterRead="afterRead(2,$event)" @delete="(event, type) => deletePic(event, 2)"
					multiple :maxCount="4" width="210rpx" height="210rpx" :fileList="sliderArr"
					:sizeType="['compressed']">
				</u-upload>
			</u-form-item>
			<view>
				<view style="font-weight: bold; font-size: 14px;display: flex;display: flex;align-items: center;">
					<text style="margin-right: 30rpx;">商品规格</text>
					
					<u-radio-group v-model="attrType" placement="row">
						<u-radio v-for="(item, index) in range":key="index" :label="item.text" :name="item.value"></u-radio>
					</u-radio-group>
				</view>


			</view>
			<view class="" v-if="attrType==1">


				<view v-for="(item, index) in form.attrs" :key="index"
					style="padding: 20rpx; margin-bottom: 20rpx; background: rgba(0, 0, 0, .1); box-shadow: 0 12px 10px -10px rgba(0,0,0,.1);">
					<u-form :model="form.attrs[index]" :errorType="['message', 'toast']" ref="subformRef"
						labelWidth='160rpx' :rules="subformItemRules">
						<u-form-item label="商品图片" prop="pic">
							<u-upload accept="image" @afterRead="afterRead(3,$event)"
								@delete="(event, type) => deletePic(event, 3)" multiple :maxCount="1" width="150rpx"
								height="150rpx" :fileList="picArr" :sizeType="['compressed']">
							</u-upload>
						</u-form-item>
						<u-form-item label="门店价" prop="ot_price" borderBottom>
							<u--input v-model="item.ot_price" name="input" type="digit"></u--input>
						</u-form-item>
						<u-form-item label="会员价" prop="price" borderBottom>
							<u--input v-model="item.price" name="input" type="digit"></u--input>
						</u-form-item>
						<u-form-item label="库存" prop="stock" borderBottom>
							<u--input v-model="item.stock" name="input" type="number"></u--input>
						</u-form-item>
						<u-form-item label="商品编号" prop="bar_code" borderBottom>
							<u--input v-model="item.bar_code" name="input"></u--input>
						</u-form-item>
						<u-form-item label="重量(kg)" prop="weight" borderBottom>
							<u--input v-model="item.weight" name="input" type="digit"></u--input>
						</u-form-item>
						<u-form-item label="体积(m³)" prop="volume" borderBottom>
							<u--input v-model="item.volume" name="input" type="digit"></u--input>
						</u-form-item>
					</u-form>
				</view>

			</view>
			<view class="" v-if="attrType==2">
				<view class="">
					<u-form :model="form" :errorType="['message', 'toast']" ref="subformRef" labelWidth='160rpx'>
						<u-form-item borderBottom>
							<view>
								<u-form-item label="规格">
									<u-input placeholder="请输入规格" border='surround' v-model="formDynamic.attrsName">
									</u-input>
								</u-form-item>
								<u-form-item label="规格值">
									<u-input placeholder="请输入规格值" border='surround' v-model="formDynamic.attrsVal">
									</u-input>
								</u-form-item>
								<u-form-item>
									<view class="flex">
										<view class="" style="width: 100rpx;margin-right: 20rpx;">
											<u-button text="确定" @click="addDynamic()" type="primary"
												size="small"></u-button>
										</view>
										<view class="" style="width: 100rpx;">
											<u-button text="取消" type="error"
												size="small"></u-button>
										</view>
									</view>
								</u-form-item>
							</view>

							<view class="flex">
								<view class="" style="width: 200rpx;margin-right: 20rpx;">
									<u-button text="添加新规格" type="primary" size="small"></u-button>
								</view>
								<view class="" style="width: 160rpx;">
									<u-button text="立即生成" type="success" @click="generation()" size="small"></u-button>
								</view>

							</view>
							<scroll-view scroll-x style="width:710rpx;" scroll-with-animation="true"
								show-scrollbar="true">
								<uni-table border stripe emptyText="暂无更多数据">
									<!-- 表头行 -->
									<uni-tr>
										<uni-th align="center" v-for="(item,index) in head"
											:key="index">{{item.title}}</uni-th>
									</uni-tr>
									<!-- 表格数据行 -->
									<uni-tr v-for="(item,index) in table" :key="index">
										<uni-td align="center" v-for="(item1,index1) in item.title" :key="index">
											{{item1}}
										</uni-td>
										<uni-td align="center">
											<u-upload accept="image" @afterRead="afterRead(3,$event)"
												@delete="(event, type) => deletePic(event, 3)" multiple :maxCount="1"
												width="120rpx" height="120rpx" :fileList="item.pic"
												:sizeType="['compressed']">
											</u-upload>
										</uni-td>
										<uni-td align="center">
											<u-number-box v-model="item.ot_price"></u-number-box>
										</uni-td>
										<uni-td align="center">
											<u-number-box v-model="item.price"></u-number-box>
										</uni-td>
										<uni-td align="center">
											<u-number-box v-model="item.cost"></u-number-box>
										</uni-td>
										<uni-td align="center">
											<u-number-box v-model="item.serviceRatio"></u-number-box>
										</uni-td>
										<uni-td align="center">
											<u-number-box v-model="item.stock"></u-number-box>
										</uni-td>
										<uni-td align="center">
											<u-input border v-model="item.bar_code" placeholder="请输入产品编号"></u-input>
										</uni-td>
										<uni-td align="center">
											<u-number-box v-model="item.weight"></u-number-box>
										</uni-td>
										<uni-td align="center">
											删除
										</uni-td>
									</uni-tr>


								</uni-table>
							</scroll-view>


						</u-form-item>
					</u-form>
				</view>
			</view>
			<u-form-item label="商品状态" borderBottom>
				<u-radio-group v-model="form.is_show" placement="row">
					<u-radio v-for="(item, index) in isShowItems":key="index" :label="item.text" :name="item.value"></u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="商品详情" borderBottom>
				<!-- 编辑器 -->
				<view
					style="height: 200rpx;padding: 15rpx;border: solid 2rpx #ccc ; border-radius: 15rpx; overflow-x: hidden;">
					<scroll-view scroll-y="true" class="scroll-Y" @click="editHtml">
						<view>
							<mp-html ref="article" container-style="padding: 10px 0,"
								:content="form.description || '点击编辑内容'" />
						</view>
					</scroll-view>
				</view>
			</u-form-item>

			<view class="uni-btn-v">
				<view class="">
					<u-button @click="formSubmit" type="primary" :loading="isLoading" loadingText="提交中..."
						text="提交审核"></u-button>
				</view>
				<view class="">
					<u-button @click="reset" text="重置表单"></u-button>
				</view>
			</view>
		</u--form>
	</view>
</template>

<script>
	import {
		getInfo
	} from "@/api/user";
	import cookie from "@/utils/store/cookie";
	import {
		yxStoreMerchantCategory,
		addOrSave,
		info
	} from "@/api/business";
	import {
		VUE_APP_API_URL
	} from "@/config";
	export default {
		data() {
			return {
				// 规格数据
				formDynamic: {
					attrsName: '',
					attrsVal: ''
				},
				ruleValue: [],
				isShowItems: [{
					"value": 1,
					"text": "上架"
				}, {
					"value": 0,
					"text": "下架"
				}],
				range: [{
					"value": 1,
					"text": "单规格"
				}, {
					"value": 2,
					"text": "多规格"
				}],
				table: [],
				head: [],
				attrType: 1,
				content: '',
				imageArr: [], //封面图
				sliderArr: [], //轮播图
				picArr: [], //商品图片
				form: {
					"attrs": [ // 商品规格
						{
							"bar_code": "",
							"brokerage": 0,
							"brokerage_two": 0,
							"cost": 0,
							"detail": {},
							"ot_price": 0, // 门店价
							"pic": "",
							"pink_price": 0,
							"pink_stock": 0,
							"price": 0,
							"seckill_price": 0,
							"seckill_stock": 0,
							"servicePrice": 0,
							"serviceRatio": "",
							"stock": 0,
							"value1": "",
							"value2": "",
							"volume": 0,
							"weight": 0
						}
					],
					"bar_code": "",
					"cate_id": 33, // 生产默认传33
					"cost": 0,
					"description": "",
					"ficti": 0,
					"give_integral": 0,
					"id": 0,
					"image": "",
					"is_benefit": 0,
					"is_best": 0,
					"is_extend": 0,
					"is_good": 0,
					"is_hot": 0,
					"is_new": 0,
					"is_one_discount": 0,
					"is_postage": 0,
					"is_show": 1,
					"is_sub": 0,
					"keyword": "",
					"merId": 0,
					"otPrice": 0,
					"postage": 0,
					"price": 0,
					"product_label_one": "",
					"product_label_three": "",
					"product_label_two": "",
					"sales": 0,
					"servicePrice": 0,
					"slider_image": [],
					"sort": 0,
					"spec_type": 0,
					"stock": 0,
					"store_info": "",
					"store_name": "",
					"temp_id": 34,
					"unit_name": ""
				},
				subformItemRules: {
					'ot_price': [{
						trigger: ['change', 'blur'],
						required: true,
						message: '请输入门店价'
					}]
				},
				rules: {
					'store_name': {
						type: 'string',
						required: true,
						message: '请填写商品名称',
						trigger: ['blur', 'change']
					},

					'slider_image': {
						type: 'array',
						required: true,
						message: '请选择商品轮播图',
						trigger: ['blur', 'change']
					},
					'image': {
						type: 'string',
						required: true,
						message: '请选择商品封面图',
						trigger: ['blur', 'change']
					}
				}
			};
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.uForm.setRules(this.rules)
			// if (this.subformItemRules) {
			// 	this.$nextTick(() => {
			// 		this.$refs['subformRef']?.forEach((subform) => {
			// 			subform.setRules(this.subformItemRules);
			// 		});
			// 	});
			// }
		},
		components: {},
		mounted() {
			const id = this.$yroute.query.id
			uni.setNavigationBarTitle({
				title: id ? '修改商品' : '添加商品'
			});
			if (id) {
				this.getInfo(id)
			}

		},
		onShow() {
			if (uni.getStorageSync('content_html')) {
				this.form.description = uni.getStorageSync('content_html')
				uni.removeStorage('content_html')
			}
		},
		methods: {
			// combineArrays() {

			// 	let data = this.ruleValue //获取数据
			// 	let sku = this.table

			// 	let akxs = data.reduce((total, canpaxl) => {
			// 		console.log(total, canpaxl)
			// 		let overlappingData = []
			// 		total.forEach(item => {
			// 			canpaxl.detail.forEach(items => {
			// 				overlappingData.push(item.concat(items)) //往数组里追加item并每个都拼接下一级的数据
			// 			})
			// 		})
			// 		return overlappingData
			// 	}, [
			// 		[]
			// 	])
			// 	this.table = [] //每次进来清空表格数据

			// 	akxs.forEach((item, ind) => {
			// 		let obj = { //设置表格需要的数据
			// 			ot_price: sku[ind]?.ot_price ?? 0,
			// 			price: sku[ind]?.price ?? 0,
			// 			cost: sku[ind]?.cost ?? 0,
			// 			stock: sku[ind]?.stock ?? 0,
			// 			weight: sku[ind]?.weight ?? 0,
			// 			bar_code: sku[ind]?.bar_code ?? '',
			// 			pic: sku[ind]?.pic ?? '',
			// 			serviceRatio: sku[ind]?.serviceRatio ?? 0,
			// 		}
			// 		let name = []
			// 		data.forEach((i, index) => {
			// 			name.push(item[index])
			// 			obj['value' + index] = item[index] //追加id_属性
			// 		})
			// 		obj.title = name
			// 		this.table.push(obj)
			// 	})

			// },
			generation() {},
			// generation() {
			// 	const data = [{
			// 			title: '图片'
			// 		},
			// 		{
			// 			title: '零售价'
			// 		},
			// 		{
			// 			title: '会员价'
			// 		},
			// 		{
			// 			title: '商家价'
			// 		},
			// 		{
			// 			title: '直营管理比例'
			// 		},
			// 		{
			// 			title: '库存'
			// 		},
			// 		{
			// 			title: '产品编号'
			// 		},
			// 		{
			// 			title: '重量(KG)'
			// 		},
			// 		{
			// 			title: '操作'
			// 		},
			// 	]
			// 	for (var i = 0; i < this.ruleValue.length; i++) {
			// 		data.splice(0, 0, {
			// 			title: this.ruleValue[i].value
			// 		})
			// 	}
			// 	this.head = data

			// 	let result = this.combineArrays();
			// 	console.log('result', result)

			// },
			addDynamic() {},
			// addDynamic() {
			// 	if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
			// 		this.ruleValue.push({
			// 			detail: [this.formDynamic.attrsVal],
			// 			value: this.formDynamic.attrsName,
			// 			text: ''
			// 		})
			// 		this.formDynamic = {
			// 			attrsName: '',
			// 			attrsVal: ''
			// 		}
			// 		this.DynamicShow = false
			// 	} else {
			// 		uni.showToast({
			// 			title: '请输入规格和规格值',
			// 			icon: 'none'
			// 		});
			// 	}
			// },
			getInfo(id) {
				info(id).then(res => {
						const data = res.data.productInfo
						this.form = {
							"attrs": [data.attr],
							"bar_code": "",
							"cate_id": data.cate_id, // 分类id
							"cost": 0,
							"description": data.description, // 富文本
							"ficti": 0,
							"give_integral": 0,
							"id": data.id,
							"image": data.image, //商品封面图
							"is_benefit": 0,
							"is_best": 0,
							"is_extend": 0,
							"is_good": 0,
							"is_hot": 0,
							"is_new": 0,
							"is_one_discount": 0,
							"is_postage": 0,
							"is_show": data.is_show, // 是否上架
							"is_sub": 0,
							"keyword": "",
							"merId": data.uid,
							"otPrice": 0,
							"postage": 0,
							"price": 0,
							"product_label_one": "",
							"product_label_three": "",
							"product_label_two": "",
							"sales": 0,
							"servicePrice": 0,
							"slider_image": data.slider_image, // 商品轮播图
							"sort": data.sort, // 排序
							"spec_type": 0,
							"stock": 0,
							"store_info": data.store_info,
							"store_name": data.store_name, // 名称
							"temp_id": 34, // 运费模板 生产环境直接传递34
							"unit_name": ""
						}
						this.imageArr = this.assemblyArr(data.image)
						this.sliderArr = this.assemblyArr(data.slider_image)
						this.picArr = this.assemblyArr(data.attr.pic)

				}).catch(err => {
					console.log(err, "err")
				})
			},

			assemblyArr(data) {
				if (data == '' || data == null) return []
				let arr
				if (data.constructor === Array) {
					arr = data
					console.log("data", arr)
				} else {
					arr = data.split(',')
				}

				for (var i = 0; i < arr.length; i++) {
					arr[i] = {
						url: arr[i],
					}
				}
				console.log(arr)
				return arr
			},
			//删除图片
			deletePic({
				index
			}, type) {
				let arr
				if (type == 1) {
					this.imageArr.splice(index, 1)
				} else if (type == 2) {
					this.sliderArr.splice(index, 1)
				} else if (type == 3) {
					this.picArr.splice(index, 1)
				}

			},
			customUpdate(filePath, arr) {
				console.log(filePath)
				const self = this
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `${VUE_APP_API_URL}/api/qiNiuContent`,
						filePath: filePath,
						name: 'file',
						formData: {
							bucketName: 'bucket2',
							storeFileName: 'file',
							saveSql: '1'
						},
						header: {
							'token': cookie.get('login_status'),
							// 'token': 'a82472c6-96c9-46b0-a018-783dea7864b5',
							'content-type': 'multipart/form-data' // 默认值
						},
						success: uploadFileRes => {
							if (uploadFileRes.statusCode === 200) {
								var dataResult = JSON.parse(uploadFileRes.data).data;
								resolve(dataResult)
							} else {
								arr.splice(arr.length - 1, 1)
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							}
						},
						fail() {
							arr.splice(arr.length - 1, 1)
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					})
				})
			},
			// 新增图片
			async afterRead(status, event) {
				let arr
				if (status == 1) {
					arr = this.imageArr
				} else if (status == 2) {
					arr = this.sliderArr
				} else {
					arr = this.picArr
				}
				const size = (event.file[0].size) / 1024 / 1024
				if (size > 2) {
					return this.$u.toast('上传图片大小不能超过2MB')
				}

				let lists = [].concat(event.file)

				// 记录图片数组起点索引
				let fileListLen = arr.length

				lists.map((item) => {
					arr.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.customUpdate(lists[i].url, arr)
					let item = arr[fileListLen]
					arr.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result[0],
						filePath: result[0]
					}))
					console.log(arr)
					if (status == 1) {
						this.picArr.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result[0],
							filePath: result[0]
						}))
					}
					fileListLen++
				}
			},
			//跳转富文本
			editHtml() {
				cookie.set('content_html', this.content);
				this.$yrouter.push({
					path: "/storeManagementPack/pages/edit_html/index",
				});
			},
			//图片转字数组
			imageArrSalvage(arr) {
				if (arr.length <= 0) return
				let Array = []
				for (var i = 0; i < arr.length; i++) {
					Array.push(arr[i].url)
				}
				return Array
			},
			reset() {
				this.imageArr = []
				this.sliderArr = []
				this.picArr = []
				this.form = this.$options.data().form;
				console.log(this.form)
			},
			// 验证所有的子表单
			checkSubformValid() {
				let formFlag = true;
				return new Promise((resolve, reject) => {
					let list = [];
					this.$refs['subformRef'].forEach((subform) => {
						const p = new Promise((reso, rej) => {
							subform.validate((valid) => {
								if (!valid) {
									formFlag = false;
								}
								reso(); // 单个接口执行完毕
							});
						});
						list.push(p);
					});
					Promise.all(list).then((result) => {
						resolve(formFlag); // 所有接口都执行完毕
					});
				});
			},
			//提交
			async formSubmit(e) {


				let that = this
				this.form.attrs[0].pic = this.picArr.length ? this.picArr[0].url : ''
				this.form.image = this.imageArr.length ? this.imageArr[0].url : ''
				this.form.slider_image = this.imageArrSalvage(this.sliderArr)

				// const subformvalid = await this.checkSubformValid();
				// console.log(subformvalid)
				this.$refs.uForm.validate().then(res => {
					let isAttrs = true
					let isAttrsMsg = ""
					for (let i = 0; i < this.form.attrs.length; i++) {
						const item = this.form.attrs[i]
						// 判断商品规格字段是否必填
						if (item.ot_price <= 0) {
							isAttrs = false
							isAttrsMsg = "门店价必须大于0"
						}
						if (item.price <= 0) {
							isAttrs = false
							isAttrsMsg = "商品会员价必须大于0"
						}
						if (item.stock <= 0) {
							isAttrs = false
							isAttrsMsg = "库存必须大于0"
						}
					}
					if (!isAttrs) return uni.showToast({
						title: isAttrsMsg,
						icon: 'none'
					});

					addOrSave(this.form).then(res => {
						uni.showToast({
							title: '操作成功',
							icon: 'none'
						});
						setTimeout(function() {
							that.$yrouter.replace({
								path: "/storeManagementPack/pages/storeManagement/index",
								query: {
									index: 1
								}
							});
						}, 500);
					})
				}).catch(errors => {
					console.log(errors)
				})


			}
		},
	};
</script>
<style scoped lang="less">
	/deep/.u-radio{
		margin-right: 15rpx;
	}
	.flex {
		display: flex;

	}

	.wrap {
		flex-wrap: wrap;
	}
</style>